﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CharitiesLib;
using Charities.ModelViews;
using System.IO;
using System.Data.SqlClient;

namespace Charities.Forms
{
    public partial class FormMDI : Form
    {
        MainWindow m = null;
        MainSettings ms = null;
        WorthiesTypes w = null;
        Login l = null;
        AboutFrm ab = null;
        ModelContainer ctx = new ModelContainer();
        EntriesReport en = null;
        GreantsReportsAll gra = null;
        SuppliesInWhereHouse siw = null;
        TrackWorthyUserForm t = null;
        Inspectors_Worthies_Report iwR = null;
        WorthiesNamesReport wnR = null;


        private int userid;
        public bool is_loaded = false;

        public FormMDI(int uid)
        {
            userid = uid;
            InitializeComponent();
        }

        private void MainWindow_Load(object sender, EventArgs e)
        {
            is_loaded = true;
            User user = ctx.Users.Single(u => u.Id == userid);
            
            
            if (ctx.CharityInfos.Count()>0)
            {
                CharityInfo chart = ctx.CharityInfos.First();
                this.Text = "برنامج أهل الخير - جمعية:" + " " + chart.CharityName + " - أهلا بالمستخدم:" + "  " + user.username;
            }
            else
            {
                this.Text += " " + user.username;
            }
            foreach (var Item in user.Role.Permissions)
            {
                switch (Item.Name.Trim())
                {
                    case "MDI_WORTHIES":
                        toolStripNewWorthy.Visible = true;
                        break;
                    case "MDI_WORTHY_TYPE":
                        toolStripWorthiesTypes.Visible = true;
                        break;
                    case "MDI_SUPPLY_TYPE":
                        toolStripSypplyType.Visible = true;
                        break;
                    case "MDI_SUPPIES":
                        toolStripNewSupply.Visible = true;
                        break;
                    case "MDI_CARTS_MGMT":
                        toolStripNewBasketDetails.Visible = true;
                        break;
                    case "MDI_ROLES_MGMT":
                        toolStripRolesList.Visible = true;
                        tsbDBConnection.Visible = true;
                        break;
                    case "MDI_USERS_MGMT":
                        toolStripChangePassword.Visible = true;
                        break;
                    case "MDI_PWD_CHANGE":
                        toolStripChangeUserPWD.Visible = true;
                        break;
                    case "MDI_INSPECTORS":
                        toolStripInspector.Visible = true;
                        break;
                    case "MDI_ADVANCED_SEARCH":
                        toolStripButtonGroupOperations.Visible = true;
                        break;
                    case "MDI_SCHEDUALS":
                        toolStripButtonShceduals.Visible = true;
                        break;
                    case "MDI_TRACKING":
                        toolStripButtontrackingUserWorthy.Visible = true;
                        break;
                    case "MDI_MAINSETTINGS":
                        toolStripButtonMainSettings.Visible = true;
                        break;
                    case "MDI_ALLREPORTS":
                        toolStripDropDownReports.Visible = true;
                        break;
                    case "MDI_WORTHY_REPORTS":
                        ReportWorthy_NamesToolStripMenuItem.Visible = true;
                        break;
                    case "MDI_INSPECTORS_NAMES_REPORT":
                        ReportInspectors_ToolStripMenuItem.Visible = true;
                        break;
                    case "MDI_SUPPLIES_REPORT":
                        ReportSuppliesInWhereHouse_ToolStripMenuItem.Visible = true;
                        break;
                    case "MDI_GRANTS_REPORT":
                        Report_Grants_ToolStripMenuItem.Visible = true;
                        break;
                    case "MDI_ENTRIES":
                        Report_Entries_BatchesToolStripMenuItem.Visible = true;
                        break;
                    case "MDI_SYNC":
                        SynctoolStripButton.Visible = true;
                        break;
                    case "MDI_WINDOWS":
                        openedWindowsToolStripButton.Visible = true;
                        break;
                    case "MDI_LOGIN":
                        toolStripButtonSwitchUAccount.Visible = true;
                        break;
                    case "MDI_ABOUT":
                        Abouttoolstrip.Visible = true;
                        break;
                    default:
                        break;
                }
            }


        }
        private void toolStripNewWorthy_Click(object sender, EventArgs e)
        {
            if (m != null && m.is_loaded)
                m.Activate();
            else
            {
                m = new MainWindow(userid, this,false);
                m.Show();
            }
        }
        SupplyTypes supt = null;
        private void toolStripSypplyType_Click(object sender, EventArgs e)
        {
            if (supt != null && supt.is_loaded)
                supt.Activate();
            else
            {
                supt = new SupplyTypes(userid, this);
                supt.Show();
            }
        }
        Supplies supf = null;
        private void toolStripNewSupply_Click(object sender, EventArgs e)
        {
            if (supf != null && supf.is_loaded)
                supf.Activate();
            else
            {
                supf = new Supplies(userid, this);
                supf.Show();
            }

        }
        CartsEditor ce = null;
        private void toolStripNewBasketDetails_Click(object sender, EventArgs e)
        {
            if (ce != null && ce.is_loaded)
                ce.Activate();
            else
            {
                ce = new CartsEditor(userid, this);
                ce.Show();
            }
        }
        RolesMgmt rmgt = null;
        private void toolStripRolesList_Click(object sender, EventArgs e)
        {
            if (rmgt != null && rmgt.is_loaded)
                rmgt.Activate();
            else
            {
                rmgt = new RolesMgmt(userid, this);
                rmgt.Show();
            }
        }

        UsersMgmt umgt = null;
        private void toolStripChangePassword_Click(object sender, EventArgs e)
        {
            if (umgt != null && umgt.is_loaded)
                umgt.Activate();
            else
            {
                umgt = new UsersMgmt(userid, this);
                umgt.Show();
            }
        }


        private void toolStripButtonWorthyTypes_Click(object sender, EventArgs e)
        {
            if (w != null && w.is_loaded)
                w.Activate();
            else
            {
                w = new WorthiesTypes(userid, this);
                w.Show();
            }
        }
        Inspectors ins = null;
        private void toolStripInspector_Click(object sender, EventArgs e)
        {
            if (ins != null && ins.is_loaded)
                ins.Activate();
            else
            {
                ins = new Inspectors(userid, this);
                ins.Show();
            }
        }

        ChangePasswordDlg chpd = null;
        private void toolStripChangeUserPWD_Click(object sender, EventArgs e)
        {
            if (chpd != null && chpd.is_loaded)
                chpd.Activate();
            else
            {
                chpd = new ChangePasswordDlg(userid, this);
                chpd.Show();
            }
        }
        private string trimstring(string str)
        {
            string temp = str.Replace(':', '_');
            temp = temp.Replace(' ', '_');
            return temp;
        }


        private void MainWindow_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }
        Forms.CustomOperationsSearch cos = null;
        private void toolStripButtonGroupOperations_Click(object sender, EventArgs e)
        {
            if (cos != null && cos.is_loaded)
                cos.Activate();
            else
            {
                cos = new Forms.CustomOperationsSearch(userid, this);
                cos.Show();
            }
        }
        Forms.Shceduals shed = null;
        private void toolStripButtonShceduals_Click(object sender, EventArgs e)
        {
            if (shed != null && shed.is_loaded)
                shed.Activate();
            else
            {
                shed = new Forms.Shceduals(userid, this);
                shed.Show();
            }
        }
        GrantsReport g = null;
        private void btn_emptyGrantReport_Click(object sender, EventArgs e)
        {

            if (g != null && g.is_loaded)
                g.Activate();
            else
            {
                g = new GrantsReport(this);
                g.Show();
            }
        }

        private void toolStripButtontrackingUserWorthy_Click(object sender, EventArgs e)
        {
         
            if (t != null && t.is_loaded)
                t.Activate();
            else
            {
                t = new TrackWorthyUserForm(userid,this);
                t.Show();
            }
        }

        private void toolStripButtonSwitchUAccount_Click(object sender, EventArgs e)
        {
            if (l != null && l.is_loaded)
                l.Activate();
            else
            {
                l = new Login(this);
                l.Show();
            }
        }

        private void toolStripButtonExit_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("هل أنت متأكد من اغلاق البرنامج", "تأكيد إنهاء البرنامج", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                Application.Exit();
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (ab != null && ab.is_loaded)
                ab.Activate();
            else
            {
                ab = new AboutFrm();
                ab.Show();
            }
        }

        private void toolStripButtonMainSettings_Click(object sender, EventArgs e)
        {
            if (ms != null && ms.is_loaded)
                ms.Activate();
            else
            {
                ms = new MainSettings(this);
                ms.Show();
            }
        }

        private void ReportWorthy_NamesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (wnR != null && wnR.is_loaded)
                wnR.Activate();
            else
            {
                wnR = new WorthiesNamesReport(userid,this);
                wnR.Show();
            }
        }

        private void ReportInspectors_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (iwR != null && iwR.is_loaded)
                iwR.Activate();
            else
            {
                iwR = new Inspectors_Worthies_Report(userid,this);
                iwR.Show();
            }
        }

        public void addFormToWindowsList(Form frm)
        {
            // uncheck all items
            uncheckAllOpenedWindowsListItems();

            // add form to opend windows list
            openedWindowsToolStripButton.DropDownItems.Add(frm.Text);

            // check current form
            ((ToolStripMenuItem)openedWindowsToolStripButton.DropDownItems[openedWindowsToolStripButton.DropDownItems.Count - 1]).Checked = true;

            // disbale scaling of image
            ((ToolStripMenuItem)openedWindowsToolStripButton.DropDownItems[openedWindowsToolStripButton.DropDownItems.Count - 1]).ImageScaling = ToolStripItemImageScaling.None;

            // assign current form to tag of item
            ((ToolStripMenuItem)openedWindowsToolStripButton.DropDownItems[openedWindowsToolStripButton.DropDownItems.Count - 1]).Tag = frm;
        }

        public void removeFormFromWindowsList(Form frm)
        {
            // remove item
            for (int i = 0; i < openedWindowsToolStripButton.DropDownItems.Count; i++)
                if (openedWindowsToolStripButton.DropDownItems[i].Text == frm.Text)
                    openedWindowsToolStripButton.DropDownItems.RemoveAt(i);
        }

        private void openedWindowsToolStripButton_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            // uncheck all items
            uncheckAllOpenedWindowsListItems();

            // get clicked form
            if (e.ClickedItem.Tag.ToString() != "Operation")
            {
                Form frm = (Form)e.ClickedItem.Tag; 
                // check the clicked item
            ((ToolStripMenuItem)e.ClickedItem).Checked = true;

            // activate the form
            frm.Activate();
            }
                     

           
        }

        public void activateWindow(Form frm)
        {
            try
            {
                uncheckAllOpenedWindowsListItems();

                for (int i = 0; i < openedWindowsToolStripButton.DropDownItems.Count; i++)
                    if (openedWindowsToolStripButton.DropDownItems[i].Text == frm.Text)
                        ((ToolStripMenuItem)openedWindowsToolStripButton.DropDownItems[i]).Checked = true;

                // activate the form
                frm.Activate();
            }
            catch (Exception)
            {
            }
            // uncheck all items
        }

        // uncheck all opened windows items
        private void uncheckAllOpenedWindowsListItems()
        {
            for (int j = 0; j < openedWindowsToolStripButton.DropDownItems.Count; j++)
                if(openedWindowsToolStripButton.DropDownItems[j] is ToolStripMenuItem)
                if (((ToolStripMenuItem)openedWindowsToolStripButton.DropDownItems[j]).Checked)
                    ((ToolStripMenuItem)openedWindowsToolStripButton.DropDownItems[j]).Checked = false;
        }

        private void Report_Entries_BatchesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if ( en != null && en.is_loaded )
            {
                en.Activate();
            }
            else
            {
                en = new EntriesReport(userid, this);
                en.Show();
            }
        }

        private void Report_Grants_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (gra != null && gra.is_loaded)
            {
                gra.Activate();
            }
            else
            {
                gra = new GreantsReportsAll(userid, this);
                gra.Show();
            }
        }

        private void ReportSuppliesInWhereHouse_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (siw != null && siw.is_loaded)
            {
                siw.Activate();
            }
            else
            {
                siw = new SuppliesInWhereHouse(userid, this);
                siw.Show();
            }
        }

        private void FormMDI_Activated(object sender, EventArgs e)
        {
            // activate this form and add it windows list as activate one
          //  ((Forms.FormMDI)this.MdiParent).activateWindow(this);
        }

        private void CloseAllFormsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            for (int j = 0; j < openedWindowsToolStripButton.DropDownItems.Count; j++)
            {
                if (openedWindowsToolStripButton.DropDownItems[j] is ToolStripMenuItem)
                {
                    if (((ToolStripMenuItem)openedWindowsToolStripButton.DropDownItems[j]).Tag.ToString() != "Operation")
                    {
                        openedWindowsToolStripButton.DropDownItems.RemoveAt(j);
                    }
                }
            }
            foreach (Form aForm in this.MdiChildren)
            {
                aForm.Close();
            }
        
        }

        private void MaxemizToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form aForm in this.MdiChildren)
            {
                aForm.WindowState = FormWindowState.Maximized;
            }
        }

        private void MinimizeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form aForm in this.MdiChildren)
            {
                aForm.WindowState = FormWindowState.Minimized;
            }
        }

        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form aForm in this.MdiChildren)
            {
                aForm.WindowState = FormWindowState.Normal;
            }
            
        }
        SyncForm syf = null;
        private void SynctoolStripButton_Click(object sender, EventArgs e)
        {
            if (syf != null && syf.is_loaded)
            {
                syf.Activate();
            }
            else
            {
                syf = new SyncForm(userid, this);
                syf.Show();
            }
        }

        private void tsbDBConnection_Click(object sender, EventArgs e)
        {
            DialogResult res= MessageBox.Show("قد تؤدي هذه العملية لتغيير وأخطاء في عملية الاتصال , هل أنت متأكد؟","تأكيد تغيير اعدادات الاتصال",MessageBoxButtons.YesNo);
            if (res == DialogResult.Yes)
            {
                Forms.ConnetionBuilder con = new ConnetionBuilder();
                con.Show();
                this.Hide();
            }
        }

        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            SqlCommand com = new SqlCommand();
            SqlConnection con = new SqlConnection();
            con.ConnectionString = "Data Source=ADVHASSE\\SQLSERVER;Initial Catalog=Charities;Integrated Security=True";
            com.Connection = con;
            com.CommandText = "SELECT * FROM [Charities].[dbo].[ImportedWorthy]";
            com.Connection.Open();
            IDataReader dr=com.ExecuteReader();
            try
            {
                while (dr.Read())
                {
                    Worthy wor = new Worthy();
                    Person p = new Person();
                    
                    string fulln=dr["FullName"].ToString();
                    toolStripLabel1.Text = fulln;
                    string[] FullName = fulln.Split();
                    if ((fulln.Contains("عبد") && !fulln.Contains("عبدو")) || fulln.Contains("أبو")
                        || fulln.Contains("محي") || fulln.Contains("ابو")
                        || fulln.Contains("الشيخ"))
                    {
                        int indx = -1;
                        if (fulln.Contains("عبد ا"))
                        {
                            indx = fulln.IndexOf("عبد ا");
                            fulln = fulln.Remove(indx + 3, 1);
                        }
                        if (fulln.Contains("محي"))
                        {
                            indx = fulln.IndexOf("محي");
                            fulln = fulln.Remove(indx + 3, 1);

                        }
                        if (fulln.Contains("الشيخ "))
                        {
                            indx = fulln.IndexOf("الشيخ ");
                            fulln = fulln.Remove(indx + 5, 1);

                        }
                        FullName = fulln.Split();
                        for (int i = 0; i < FullName.Count(); i++)
                        {
                            if (FullName[i].Contains("محي"))
                            {
                                FullName[i] = FullName[i].Insert(FullName[i].IndexOf("محي") + 3, " ");

                            }
                            if (FullName[i].Contains("الشيخ"))
                            {
                                FullName[i] = FullName[i].Insert(FullName[i].IndexOf("الشيخ ") + 6, " ");

                            }
                        }
                    }

                    int size = FullName.Count();

                    if ((FullName[0].Contains("عبد") && !FullName[0].Contains("عبدو")) 
                        || FullName[0].Contains("ابو") 
                        || FullName[0].Contains("أبو")
                        || FullName[0].Contains("محي"))
                    {
                        if (size < 3)
                        {
                            p.FirstName = FullName[0];
                            p.LastName = FullName[1];
                            p.FatherName = "";
                        }
                        else if (size < 4)
                        {
                            p.FirstName = FullName[0] + " " + FullName[1];
                            p.LastName = FullName[2];
                        }
                        else if (size < 5)
                        {
                            p.FirstName = FullName[0] + " " + FullName[1];
                            p.FatherName = FullName[2];
                            p.LastName = FullName[3];
                        }
                        else
                        {
                            p.FirstName = FullName[0];
                            p.FatherName = FullName[1];
                            string str = string.Empty;
                            for (int i = 2; i <= size; i++)
                            {

                                str += FullName[i] + " ";
                                p.LastName = str.Trim();
                            }
                        }
                    }
                    else
                    {
                        if (size < 3)
                        {
                            p.FirstName = FullName[0];
                            p.LastName = FullName[1];
                            p.FatherName = "";
                        }
                        else if (size < 4)
                        {
                            p.FirstName = FullName[0];
                            p.FatherName = FullName[1];
                            p.LastName = FullName[2];
                        }
                        else if (size < 5)
                        {
                            p.FirstName = FullName[0];
                            p.FatherName = FullName[1];
                            p.LastName = FullName[2] + " " + FullName[3];
                        }
                        else 
                        {
                            p.FirstName = FullName[0];
                            p.FatherName = FullName[1];
                            string str = string.Empty;
                            for (int i = 2 ; i <= size; i++)
                            {
                                
                                str += FullName[i] + " " ;
                                p.LastName = str.Trim();
                            }

                        }
                    }
                    p.MotherName = dr["motherName"].ToString();
                    p.NationalNumber = dr["nationalNumber"].ToString();
                    p.Qaid = dr["City"].ToString();
                    p.Amana = dr["City"].ToString();
                    p.JobTitle = dr["job"].ToString();
                    p.HealthStatus = dr["healthstatus"].ToString();
                    p.MaritalStatus = dr["sotialStatus"].ToString();
                    p.RelationshipWithWorthy = "المستحق";
                    wor.CurrentAddress = dr["Address"].ToString();
                    wor.InsertUId = userid;
                    wor.InsertDate = DateTime.Parse(dr["InsertDate"].ToString());
                    string inspector = dr["inspector"].ToString();
                    if (ctx.Inspectors.Where(i => i.Name == inspector).Count() == 0 && inspector != null && inspector != "")
                    {
                        wor.Inspector = new Inspector { Name = inspector, InsertDate = DateTime.Now, InsertUId = userid };
                    }
                    else
                    {
                        wor.Inspector = ctx.Inspectors.Where(i => i.Name == inspector).First();
                    }
                    wor.IsActive = true;
                    wor.Phone = dr["Mobile"].ToString();
                    wor.FamilyNumber = dr["familyCardName"].ToString();
                    string worthyType = dr["worthyType"].ToString();
                    if (ctx.WorthyTypes.Where(i => i.Name == worthyType).Count() == 0 && worthyType != null && worthyType != "")
                    {
                        wor.WorthyType = new WorthyType { Name = worthyType, InsertDate = DateTime.Now, InsertUId = userid };
                    }
                    else
                    {
                        wor.WorthyType = ctx.WorthyTypes.Where(i => i.Name == worthyType).First();
                    }
                    wor.People.Add(p);
                    ctx.Worthies.Add(wor);
                    ctx.SaveChanges();
                    wor.PersonId = p.Id;
                 
                }
            }
            catch
            {
                
                
            }
            ctx.SaveChanges();
            com.Connection.Close();
            Cursor = Cursors.Default;
        }
        frmHelp foh = null;
        private void tspHelp_Click(object sender, EventArgs e)
        {
            if (foh != null && foh.is_loaded)
            {
                foh.Activate();
            }
            else
            {
                foh= new frmHelp(this);
                foh.Show();
            }
        }
    }
}
